<?php 
/**
 * 用户管理中心
 * @author Nonant
 *
 */

class AccountAction extends BaseAction{
    
	function _initialize(){
    	parent::_initialize();
    }
    
    function namecard(){
    	exit;
    }
    
    public function profile(){
    	$userInfo = M('user')->where('id='.$this->mid)->find();
    	$this->assign('userInfo', $userInfo);
		$this->display();
	}
		
	public function saveProfile(){

		//参数合法性检查
		$required_field = array(
			'uname'		=> '昵称'
		);
		foreach ($required_field as $k => $v) {
			if ( empty($_POST[$k]) ) $this->error($v . '不可为空');
		}

		$map['uname']	    = t($_POST['uname']);
		$res = M('user')->where("uname='".$map['uname']."' and id!=".$this->mid)->count();
		if ( !$res ) {
		}else {
			$this->error('昵称已经被使用，请重新输入');
		}

		$map['realname']	= t($_POST['realname']);
		$map['gender']	  = t($_POST['gender']);
				
		$map['address']	  = t($_POST['address']);
		$map['zipcode']	  = t($_POST['zipcode']);
		$map['is_open'] 	= t($_POST['is_open']);
		$gparea = explode(',',$_POST['gparea']);
		$btime	    = $_POST['btime'];
		//echo 'btime='.$btime.'<br>';
		if(!empty($btime))$btime = paramDate($btime);
		//echo 'btime='.$btime.'<br>';
		if(!empty($btime))$map['btime'] = $btime;
		//echo 'btime='.$btime.'<br>';
		if(!empty($gparea[0])) {
			$map['province_id'] 	=	intval($gparea[0]);
			$map['city_id'] 	=	intval($gparea[1]);
			$map['area_id'] 	=	intval($gparea[2]);
		 }
				
		$map['id']	    = $this->mid;
		$map['mtime']	  = time();
		$dao = M('user');
		$uid = $dao->save($map);
		if (!$uid) $this->error('修改失败，请稍后重试');
		$this->success('修改成功');
	}
    
	public function security(){
		// 豆瓣登陆
		include_once QUICK_ADDONE_PATH.'/plugins/login/douban.class.php';
		$douban = new douban();
		$this->assign('doubanurl', $douban->getUrl(SITE_URL.U('User://Account/doubanCallback')));
		
		// 新浪登陆
		include_once( QUICK_ADDONE_PATH.'/plugins/login/sina.class.php' );
		$sina = new sina();
		$this->assign('sinaurl',$sina->getUrl(SITE_URL.U('User://Account/sinaCallback')));
		
		$this->display();
	}
	
	
	/**
	 * 绑定第三方账号回调函数。
	 */
	public function sinaCallback(){
		include_once( QUICK_ADDONE_PATH.'/plugins/login/sina.class.php' );
		$sina = new sina();
		$sina->checkUser();
		$this->bindaccount('sina');
	}
	
	public function doubanCallback() {
		$this->assign('notJump', 'yes');
		if ( !isset($_GET['oauth_token']) ) {
			$this->error('Error: No oauth_token detected.');
			exit;
		}
		require_once QUICK_ADDONE_PATH.'/plugins/login/douban.class.php';
		$douban = new douban();
		if ( $douban->checkUser($_GET['oauth_token']) ) {
			$this->bindaccount('douban');
		}else {
			$this->error('验证失败');
		}
	}
	
	/**
	 * 取消第三方绑定
	 */
	public function unbindaccount(){
		$type = $_POST['type'];
		if ( ! in_array($type, array('douban','sina')) ) {
			$this->error('参数错误');
		}
		
		$user1 = M('User')->where("id='".$_SESSION['mid']."'")->find();
		if( empty($user1) ){
			$this->error('用户不存在');
		}else{
			if($user1['sync_type']==$type){
				$this->error($type.'直接登录用户，不能取消绑定');
			}
		}
		$map['type']=$type;
		$map['uid']=$_SESSION['mid'];
		$result=M('login')->where($map)->delete();
		//dump($result);
		if ($result) {
			$this->success('取消绑定成功'.$type);		
		}else {
			$this->error('取消绑定失败'.$type);
		}
		exit;
	}
	
	private function bindaccount($type) {
		$this->assign('notJump', 'yes');
		if ( ! in_array($type, array('douban','sina')) ) {
			$this->error('参数错误');
		}
		
		include_once( QUICK_ADDONE_PATH."/plugins/login/{$type}.class.php" );
		$platform = new $type();
		$userinfo = $platform->userInfo();
		
		// 检查是否成功获取用户信息
		if ( !is_numeric($userinfo['id']) || !is_string($userinfo['uname']) ) {
			$this->error('获取用户信息失败');
		}
		// 检查是否已加入本站
		$map['type_uid'] = $userinfo['id'];
		$map['type']     = $type;
		if ( ($local_uid = M('login')->where($map)->getField('uid')) && (M('User')->where('id='.$local_uid)->find()) ) {
			$this->error('该'.$type.'账号已绑定');
		}
			
		$syncdata['uid']      = $_SESSION['mid'];
		$syncdata['type_uid'] = $userinfo['id'];
		$syncdata['type']     = $type;
		//dump($syncdata);
		if ( M('login')->add($syncdata) ) {
			$this->success('绑定成功'.$type);		
		}else {
			$this->error('绑定失败'.$type);
		}
	}
	
	//修改密码
    public function doModifyPassword() {
	    if( strlen($_POST['password']) < 6 || strlen($_POST['password']) > 16 || $_POST['password'] != $_POST['repassword'] ) {
			//$this->error('密码必须为6-16位，且两次必须相同');
			exit(json_encode(array('status'=>'-1','title'=>'','msg'=>'密码必须为6-16位，且两次必须相同'.$_POST['password'].'|'.$_POST['repassword'])));
		}
		if ($_POST['password'] == $_POST['oldpassword']) {
			exit(json_encode(array('status'=>'-1','title'=>'','msg'=>'原始密码和新密码不应该相同')));
			//$this->error('原始密码和新密码不应该相同');
		}
		
    	$dao = M('user');
		$_POST['oldpassword'] = md5($_POST['oldpassword']);
		$map['id']			  = $this->mid;
		$map['password']	  = $_POST['oldpassword'];
	    if ( $dao->where($map)->find() ) {
	    	$_POST['password']    = md5($_POST['password']);
			if ( $dao->where($map)->setField('password', $_POST['password']) ) {
				exit(json_encode(array('status'=>'1','title'=>'','msg'=>'保存成功')));
				//$this->success('保存成功');
			}else {
				exit(json_encode(array('status'=>'0','title'=>'','msg'=>'抱歉：保存失败')));
				//$this->error('抱歉：保存失败');
			}
	    }else {
	    	exit(json_encode(array('status'=>'-1','title'=>'','msg'=>'原始密码错误')));
			//$this->error('原始密码错误');
	   	}
    }
    
    //修改当前用户邮箱地址
    public function modifyEmail() {
	    $_POST['email']    = t($_POST['email']);
	    $_POST['oldemail'] = t($_POST['oldemail']);
	   	if ( !isValidEmail($_POST['email']) || !isValidEmail($_POST['oldemail']) ) {
	   		exit(json_encode(array('status'=>'-1','title'=>'','msg'=>'Email格式错误')));
	   		//echo -1;
	   		return ; //$this->error('Email格式错误');
	    }
	   	$map['id']			= $this->mid;
	   	$map['email']		= $_POST['oldemail'];
	   	if ( ! M('User')->where($map)->find() ) {
	    	exit(json_encode(array('status'=>'-2','title'=>'','msg'=>'原始Email错误')));
	    	//echo -2;
	    	return ; //原始Email错误
	    }
	   	if ( ! Model('User')->isEmailAvailable($_POST['email']) ) {
	    	exit(json_encode(array('status'=>'-3','title'=>'','msg'=>'新Emai已存在')));
	    	//echo -3;
	    	return ; //$this->error('新Emai已存在');
	    }
	    	
	   	//$opt_email_activate = model('Xdata')->lget('register');
	    	
	   	// 不需要验证邮件时, 直接修改帐号
	   	/**
		if (!$opt_email_activate['register_email_activate']) {
			if ( M('user')->where($map)->setField('email', $_POST['email']) ) {
				service('Passport')->logoutLocal();
				$json_str=json_encode(array('status'=>'1','title'=>'','msg'=>'保存成功, 请重新登陆'));
	    		//echo 1;
			}else {
				$json_str=json_encode(array('status'=>'0','title'=>'','msg'=>'保存失败'));
	    		//echo 0;
			}
			unset($opt_email_activate);
			exit($json_str);
		}
		**/	
		//unset($opt_email_activate);
				
		// 邮件验证
	    //添加验证
	    $data = array('oldemail'=>$_POST['oldemail'], 'email'=>$_POST['email']);
	    if ( $url = service('Validation')->addValidation($this->mid, '', 'Index://Public/doModifyEmail', 'modify_account', serialize($data)) ) {
	    	// 发送验证邮件
	    	global $ts;
    		$body = <<<EOD
<strong>{$ts['user']['uname']}，你好：</strong><br/>
				
您只需通过点击下面的链接重置您的帐号：<br/>
				
<a href="$url">$url</a><br/>
				
如果通过点击以上链接无法访问，请将该网址复制并粘贴至新的浏览器窗口中。<br/>
				
如果你错误地收到了此电子邮件，你无需执行任何操作来取消帐号！此帐号将不会启动。
EOD;
			
			if (service('Mail')->send_email($_POST['email'], "重置{$ts['site']['site_name']}帐号", $body)) {
				$json_str=json_encode(array('status'=>'1','title'=>'','msg'=>'激活邮件已发送，请通过邮件激活本次修改'));
	   			//echo '2';
			}else {
				$json_str=json_encode(array('status'=>'-4','title'=>'','msg'=>'验证邮件发送失败'));
	   			//echo '-4';
			}
			
    	}else {
    		$json_str=json_encode(array('status'=>'0','title'=>'','msg'=>'保存失败'));
	    			//echo '0';
    	}
    	exit($json_str);
    }


	//头像处理
    function avatar(){
        $type = $_REQUEST['t'];
        $pAvatar = D('Avatar');
        $pAvatar ->uid = $this->mid;
        if( $type == 'upload' ){
            echo $pAvatar->upload();
        }elseif ( $type == 'save'){
            $pAvatar->dosave($this->mid);
        }elseif ( $type == 'camera'){
            $pAvatar->getcamera();
        }else{
        	$this->display();
        }
    }
    
    
    /**
     * 现金账户。
     */
    function cash(){
    	exit;
    	$uamount = service('UserAccount')->get4User();
    	$this->assign('totalamount', $uamount['current_money']);
    	$this->display();
    }
    
    function ajxRefreshCash(){
    	exit;
    	$uaccount = service('UserAccount')->refresh4UserCash();
    	$uaccount['current_money_format'] = formatMoney($uaccount['current_money']);
    	$uaccount['used_money_format'] = formatMoney($uaccount['used_money']);
    	exit( json_encode(array('status'=>'1','data'=>$uaccount)) );
    }
    
 	/**
     * 用户现金。分页查询时调用。
     */
    function ajxCash(){
  		exit;
    	$this->display('cash_list_box');
    }
    
    
	/**
     * 用户积分
    
    function credit(){
    	$totalGain = service('Credit')->count4UserTotalGain();
    	//$totalUsed = service('Credit')->count4UserTotalUsed();
    	$this->assign('totalGain', $totalGain);
    	$this->assign('totalUsed', $totalUsed);
    	$this->display();
    }
    
    
    
     * 用户积分。分页查询时调用。
     
    function ajxCredit(){
    	$this->display('credit_list_box');
    }
    **/
    
    
    /**
     * 用户绑定手机。
     * 规则：绑定手机将接触已绑定的手机号。
     * 		一个手机可绑定多个账户。
     * 		先录入手机号码，然后录入验证码进行验证才可绑定。
     */
    function bindMobile(){
    	$mobile = 	t($_POST['mobile']);
    	$verify =	$_POST['verify']; 
    	if(empty($mobile))$this->error('请录入手机号码！');
    	if(!isValidMobile($mobile))$this->error('请输入正确的手机号码！');
    	if(empty($verify))$this->error('请录入验证码！');
    	$bmobile  		= $_SESSION['usertempdata']['bmobile']; 	//要验证的手机
    	$bmverify 		= $_SESSION['usertempdata']['bmverify'];	//发送的临时验证码
    	$errorno  		= intval($_SESSION['usertempdata']['errorno']); 	//验证码输入错误次数
    	$bmvsendtime 	= $_SESSION['usertempdata']['bmvsendtime'];	//验证码发送时间
    	if(empty($bmobile)||empty($bmverify)||empty($bmvsendtime))$this->error('请获取验证码！');
    	Log::record('手机绑定：['.$mobile.']['.$verify.']['.md5($verify).']['.$bmobile.']['.$bmverify.']['.$bmvsendtime.']',Log::DEBUG,Log::FILE);	
    	if(empty($bmobile)||empty($bmverify)||empty($bmvsendtime))$this->error('请获取验证码！');
		Log::save();
		if(empty($bmverify))$this->error('请先获取验证码！');
		if($errorno>3){
			$this->error('验证码录入错误已超过三次，一小时内不能进行绑定操作！');
			exit;
		}
    	if (md5($verify)==$bmverify&&$mobile==$bmobile) {
    		
	    	//如果已发送验证码，并且发送时间已过一小时，则需重新获取验证码。
	    	if( !empty($bmvsendtime) && time()-intval($bmvsendtime)>60*60 ){
	    		$this->_unsetUsertempdata();
	    		$this->error('验证码失效，请重新获取！');
	    		exit;
	    	}
    		
			$no = model('User')->bindMobile($mobile);
			Log::record('手机绑定：更新数据结果 ['.$no.']',Log::DEBUG,Log::FILE);	
			Log::save();
			if($no){
				$this->_unsetUsertempdata();
				$this->success('手机 [ '.$mobile.' ] 绑定成功 ！');
			}else{
				$this->error('手机绑定失败，请稍后再试 ！');
			}
		}else{
			$_SESSION['usertempdata']['errorno']=intval($errorno)+1;
			$this->error('验证码错误 （'.($errorno+1).'）！');
		}
		
    }
    
    private function _unsetUsertempdata(){
    	$_SESSION['usertempdata']['bmobile']	=	'';
    	$_SESSION['usertempdata']['bmverify']	=	'';
    	$_SESSION['usertempdata']['bmvsendtime']=	0;
    	$_SESSION['usertempdata']['errorno']	=	0;
    }
    
    function unBindMobile(){
    	$no = model('User')->unBindMobile();
		if($no){
			$this->success('取消手机绑定成功 ！');
		}else{
			$this->error('取消手机绑定失败，请稍后再试 ！');
		}
    }
    
    /**
     * 获得绑定手机验证码。
     * 每次执行改该操作的间隔时间为一小时。
     * 判断规则为：验证法下发时间。
     */
    function sendBMVerifyCode(){
    	$mobile = 	t($_POST['mobile']);
    	if(empty($mobile))$this->error('请录入手机号码！');
    	if(!isValidMobile($mobile))$this->error('请输入正确的手机号码！');
    	//unset($_SESSION['usertempdata']['bmvsendtime']);
    	$bmvsendtime 	= $_SESSION['usertempdata']['bmvsendtime'];
    	$bmvsendtime	= intval($bmvsendtime);
    	//如果已发送验证码，并且发送时间还未过一小时，则不能再次发送。
    	if( !empty($_SESSION['usertempdata']['bmverify']) && (time()-$bmvsendtime)<60*60 )
    		$this->error('验证码已发送，请等待。一小时内不能再次发送！');
    	
    	//生成六位随机数
    	include_once( QUICK_ADDONE_PATH.'/libs/String.class.php' );
    	$randval = String::rand_string(6,1);
    	
    	$ary_mobiles[]	=$mobile;
    	$content 		= "来自小心意：手机绑定验证码：".$randval."[小心意网]";
    	$result	= service('SendCenter')->sendSms($ary_mobiles,$content);
   
    	if($result['status']==1){
    		//验证码发送成功
    		$_SESSION['usertempdata']['bmobile']	=	$mobile;
    		$_SESSION['usertempdata']['bmverify']	=	md5($randval);
    		$_SESSION['usertempdata']['bmvsendtime']=	time();
    		$_SESSION['usertempdata']['errorno']	=	0;
    		Log::record('手机绑定验证码：['.$randval.']',Log::DEBUG,Log::FILE);	
			Log::save();
    		$this->success('请录入收到的验证码，进行手机绑定！');
    	}else{
    		$this->error('发送错误，请稍后再试！');
    	}
    }
    
    

	/**
	 * 用于外部账号直接登录后转换为系统内部账号。
	 * 流程：添加email和password即可转换为内部账号。
	 */
    function doRegisterLocal(){
    	
    	//判断用户是否为外部直接登录
    	$user1 = M('User')->where("id='".$_SESSION['mid']."'")->find();
		if( empty($user1) ){
			$this->error('用户不存在');
		}else{
			if(!empty($user1['email'])){
				$this->error('用户非外部账号直接登录');
			}
		}
		//参数合法性检查
		$required_field = array(
			'email'		=> 'Email',
			'password'	=> '密码',
			'repassword'=> '密码',
		);
    	
		foreach ($required_field as $k => $v) {
			if ( empty($_POST[$k]) ) $this->error($v . '不可为空');
		}
		
		if ( ! isValidEmail($_POST['email']) ) {
			$this->error('Email格式错误，请重新输入');
		}
		if( strlen($_POST['password']) < 6 || strlen($_POST['password']) > 16 || $_POST['password'] != $_POST['repassword'] ) {
			$this->error('密码必须为6-16位，且两次必须相同');
		}
		if ( ! model('User')->isEmailAvailable($_POST['email']) ) {
			$this->error('Email已经被使用，请重新输入');
		}
		

		$this->activate($uid, $_POST['email'], $invite);
		
		$this->success('');
    }
    
    
    
 	public function phonebook(){
    	$this->display();
	}
	
	public function ajxPhonebook(){
		$this->display("phonebook_list_box");
	}
    
	public function addPhonebook(){
		$this->display();
	}
	
	public function doModifyPbook(){
		$mobile		 = t($_POST['mobile']);
		$name		 = t($_POST['name']);
		if(!isValidMobile($mobile))$this->error('修改失败，参数错误');
		$phonebook = model('User')->getPhoneBook($_SESSION['mid'],$mobile);
		if(empty($phonebook))$this->error('修改失败，数据不存在');
		$result=model('User')->addPhoneBook($_SESSION['mid'],$mobile,$name);
		if($result>0){
			$this->success('修改成功');
		}else{
			$this->error('修改失败！');
		}
	}
	
	public function doDeletePbook(){
		$mobile		 = t($_POST['mobile']);
		if(!isValidMobile($mobile))$this->error('删除失败，参数错误');
		$phonebook = model('User')->getPhoneBook($_SESSION['mid'],$mobile);
		if(empty($phonebook))$this->error('删除失败，数据不存在');
		$result=model('User')->deletePhoneBook($_SESSION['mid'],$mobile);
		if($result>0){
			$this->success('删除成功');
		}else{
			$this->error('删除失败！');
		}
	}
	
	public function doAddPhonebook(){
		$mobile		 = t($_POST['mobile']);
		$name		 = t($_POST['name']);
		if(!isValidMobile($mobile))$this->error('手机号码错误！');
		$result=model('User')->addPhoneBook($_SESSION['mid'],$mobile,$name);
		if($result>0){
			$this->success('手机号码添加成功！');
		}else{
			$this->error('手机号码添加失败！');
		}
	}
	
	public function doAddPhonebooks(){
		$pbdata		 = t($_POST['pbdata']);
		$mobiles = explode('-$-', $pbdata);
		foreach ( $mobiles as $vo ){
			$mobile_name = explode('-!-', $vo);
			if(isValidMobile($mobile_name[0])){
				model('User')->addPhoneBook($_SESSION['mid'],$mobile_name[0],$mobile_name[1]);
			}
		}
		$this->success('手机号码添加成功！');
	}
	
	//检查电话号码是否可添加（是否已存在）
	public function isMobileAvailable() {
		$mobile		 = t($_POST['mobile']);
		
		$phonebook = model('User')->getPhoneBook($_SESSION['mid'],$mobile);
		
		if ( empty($phonebook) ) {
			echo 'success';
		}else {
			echo '手机号码已添加';
		}
		exit;
	}
	
	public function ajxSearchPbook(){
		$mobile		 = t($_POST['mobile']);
		$map['ownerid']=$_SESSION['mid'];
		$map['mobile'] = array('like','%'.$mobile.'%');
		$map['is_delete']='N';
		$result=model('User')->selectPhoneBookByMap($map, 10,'', false);
		exit(json_encode(array('status'=>'1','data'=>$result)));
	}
}
?>